package com.smart.community.property.service.impl;

import com.smart.community.commons.entity.property.UserPropertyCompany;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.property.service.IPropertyCompanyService;
import com.smart.community.property.service.IPropertyInfoService;
import com.smart.community.property.service.IUserPropertyCompanyService;
import com.smart.community.property.vo.PropertyCompanyVO;
import com.smart.community.property.vo.PropertyInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.CacheEvict;
import com.smart.community.commons.entity.property.PropertyCompany;
import java.time.LocalDateTime;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物业信息服务实现类
 * @author Wu.Liang
 * @since 2025-06-29
 */
@Slf4j
@Service
public class PropertyInfoServiceImpl implements IPropertyInfoService {

    @Autowired
    private IPropertyCompanyService propertyCompanyService;

    @Autowired
    private IUserPropertyCompanyService userPropertyCompanyService;

    @Override
    public Result<PropertyInfoVO> getCurrentUserPropertyInfo() throws Exception {
        log.info("获取当前用户的物业信息");
        
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            // 检查用户是否有关联的物业公司
            Result<Boolean> hasPropertyResult = hasPropertyCompany();
            if (!hasPropertyResult.isSuccess() || !hasPropertyResult.getData()) {
                return Result.fail("用户未关联物业公司");
            }

            // 获取用户关联的物业公司列表
            List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(userId);
            if (userPropertyCompanies == null || userPropertyCompanies.isEmpty()) {
                return Result.fail("未找到关联的物业公司");
            }

            // 获取第一个关联的物业公司ID
            Long propertyCompanyId = userPropertyCompanies.get(0).getPropertyCompanyId();
            if (propertyCompanyId == null) {
                return Result.fail("物业公司ID不能为空");
            }

            return getPropertyInfo(propertyCompanyId);
    }

    @Override
    public Result<PropertyInfoVO> getPropertyInfo(Long propertyCompanyId) throws Exception {
        log.info("获取物业公司基本信息，物业公司ID：{}", propertyCompanyId);
        
            // 获取物业公司信息
            Result<PropertyCompanyVO> propertyCompanyResult = propertyCompanyService.getPropertyCompany(propertyCompanyId);
            if (!propertyCompanyResult.isSuccess()) {
                return Result.fail("获取物业公司信息失败");
            }

            PropertyCompanyVO propertyCompanyVO = propertyCompanyResult.getData();
            if (propertyCompanyVO == null) {
                return Result.fail("物业公司信息不存在");
            }

            // 构建物业信息VO - 返回完整的物业公司信息
            PropertyInfoVO propertyInfoVO = new PropertyInfoVO();
            
            // 基本信息
            propertyInfoVO.setPropertyCompanyId(propertyCompanyVO.getId());
            propertyInfoVO.setCompanyName(propertyCompanyVO.getCompanyName());
            propertyInfoVO.setCompanyCode(propertyCompanyVO.getCompanyCode());
            propertyInfoVO.setCreditCode(propertyCompanyVO.getCreditCode());
            propertyInfoVO.setBusinessLicense(propertyCompanyVO.getBusinessLicense());
            propertyInfoVO.setLegalRepresentative(propertyCompanyVO.getLegalRepresentative());
            propertyInfoVO.setEstablishedDate(propertyCompanyVO.getEstablishedDate());
            propertyInfoVO.setRegisteredCapital(propertyCompanyVO.getRegisteredCapital());
            propertyInfoVO.setQualificationLevel(propertyCompanyVO.getQualificationLevel());
            
            // 联系信息
            propertyInfoVO.setContactPerson(propertyCompanyVO.getContactPerson());
            propertyInfoVO.setContactPhone(propertyCompanyVO.getContactPhone());
            propertyInfoVO.setContactEmail(propertyCompanyVO.getContactEmail());
            propertyInfoVO.setEmail(propertyCompanyVO.getEmail());
            propertyInfoVO.setAddress(propertyCompanyVO.getAddress());
            propertyInfoVO.setBusinessHours(propertyCompanyVO.getBusinessHours());
            propertyInfoVO.setServiceHotline(propertyCompanyVO.getServiceHotline());
            
            // 服务信息
            propertyInfoVO.setServiceScope(propertyCompanyVO.getServiceScope());
            
            // 支付信息
            propertyInfoVO.setPaymentAccount(propertyCompanyVO.getPaymentAccount());
            propertyInfoVO.setPaymentBank(propertyCompanyVO.getPaymentBank());
            propertyInfoVO.setPaymentLink(propertyCompanyVO.getPaymentLink());
            propertyInfoVO.setAlipayMerchantId(propertyCompanyVO.getAlipayMerchantId());
            propertyInfoVO.setWechatPayMerchantId(propertyCompanyVO.getWechatPayMerchantId());
            
            // 图片信息 - 确保返回完整的文件信息
            propertyInfoVO.setCompanyLogo(propertyCompanyVO.getCompanyLogo());
            propertyInfoVO.setPaymentQrCode(propertyCompanyVO.getPaymentQrCode());
            
            // 描述信息
            propertyInfoVO.setIntroduction(propertyCompanyVO.getIntroduction());
            propertyInfoVO.setDescription(propertyCompanyVO.getDescription());
            propertyInfoVO.setRemark(propertyCompanyVO.getRemark());
            
            // 状态信息
            propertyInfoVO.setStatus(propertyCompanyVO.getStatus());
            propertyInfoVO.setStatusName(propertyCompanyVO.getStatusName());
            
            // 添加调试日志，确保所有字段都被正确设置
            log.info("物业信息VO构建完成，物业公司ID：{}，公司名称：{}，公司编码：{}", 
                propertyInfoVO.getPropertyCompanyId(), 
                propertyInfoVO.getCompanyName(), 
                propertyInfoVO.getCompanyCode());
            log.info("联系信息 - 联系人：{}，电话：{}，邮箱：{}", 
                propertyInfoVO.getContactPerson(), 
                propertyInfoVO.getContactPhone(), 
                propertyInfoVO.getContactEmail());
            log.info("支付信息 - 收款账户：{}，开户银行：{}", 
                propertyInfoVO.getPaymentAccount(), 
                propertyInfoVO.getPaymentBank());
            log.info("图片信息 - 公司Logo：{}，收款二维码：{}", 
                propertyInfoVO.getCompanyLogo(), 
                propertyInfoVO.getPaymentQrCode());

            log.info("获取物业公司基本信息成功");
            return Result.success(propertyInfoVO);
    }

    @Override
    public Result<Boolean> hasPropertyCompany() throws Exception {
        log.info("检查当前用户是否有关联的物业公司");
        
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(userId);
            boolean hasProperty = userPropertyCompanies != null && !userPropertyCompanies.isEmpty();
            
            log.info("用户{}是否有关联的物业公司：{}", userId, hasProperty);
            return Result.success(hasProperty);
    }

    @Override
    @CacheEvict(value = { "propertyCompany", "propertyCompanyList", "propertyCompanyStats" }, allEntries = true)
    public Result<Void> updateCurrentUserPropertyInfo(PropertyInfoVO propertyInfoVO) throws Exception {
        log.info("更新当前用户的物业信息，参数：{}", propertyInfoVO);
        
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return Result.fail("用户未登录");
        }

        // 使用前端传递的物业公司ID，而不是获取第一个关联的物业公司
        Long propertyCompanyId = propertyInfoVO.getPropertyCompanyId();
        if (propertyCompanyId == null) {
            return Result.fail("物业公司ID不能为空");
        }

        log.info("准备更新物业公司ID：{}，用户ID：{}", propertyCompanyId, userId);

        // 检查用户是否有权限操作该物业公司
        List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(userId);
        if (userPropertyCompanies == null || userPropertyCompanies.isEmpty()) {
            return Result.fail("用户未关联物业公司");
        }

        log.info("用户关联的物业公司列表：{}", userPropertyCompanies.stream()
                .map(upc -> upc.getPropertyCompanyId())
                .collect(Collectors.toList()));

        // 检查用户是否有权限操作指定的物业公司
        boolean hasPermission = userPropertyCompanies.stream()
                .anyMatch(upc -> upc.getPropertyCompanyId().equals(propertyCompanyId));
        if (!hasPermission) {
            log.warn("用户{}无权限操作物业公司{}", userId, propertyCompanyId);
            return Result.fail("用户无权限操作该物业公司");
        }

        log.info("用户权限验证通过，开始获取物业公司实体");

        // 获取物业公司实体
        PropertyCompany propertyCompany = propertyCompanyService.getById(propertyCompanyId);
        if (propertyCompany == null) {
            log.error("物业公司不存在，ID：{}", propertyCompanyId);
            return Result.fail("物业公司不存在");
        }

        log.info("获取到物业公司实体：{}", propertyCompany.getCompanyName());

        // 更新物业公司信息
        // 基本信息
        if (propertyInfoVO.getCompanyName() != null) {
            propertyCompany.setCompanyName(propertyInfoVO.getCompanyName());
        }
        if (propertyInfoVO.getCompanyCode() != null) {
            // 检查物业公司编码唯一性（排除当前记录）
            boolean codeExists = propertyCompanyService.isCompanyCodeExists(propertyInfoVO.getCompanyCode(), propertyCompanyId);
            if (codeExists) {
                return Result.fail("物业公司编码已存在，请使用其他编码");
            }
            propertyCompany.setCompanyCode(propertyInfoVO.getCompanyCode());
        }
        if (propertyInfoVO.getCreditCode() != null) {
            propertyCompany.setCreditCode(propertyInfoVO.getCreditCode());
        }
        if (propertyInfoVO.getBusinessLicense() != null) {
            propertyCompany.setBusinessLicense(propertyInfoVO.getBusinessLicense());
        }
        if (propertyInfoVO.getLegalRepresentative() != null) {
            propertyCompany.setLegalRepresentative(propertyInfoVO.getLegalRepresentative());
        }
        if (propertyInfoVO.getEstablishedDate() != null) {
            propertyCompany.setEstablishedDate(propertyInfoVO.getEstablishedDate().atStartOfDay());
        }
        if (propertyInfoVO.getRegisteredCapital() != null) {
            propertyCompany.setRegisteredCapital(propertyInfoVO.getRegisteredCapital().doubleValue());
        }
        if (propertyInfoVO.getQualificationLevel() != null) {
            propertyCompany.setQualificationLevel(propertyInfoVO.getQualificationLevel());
        }
        
        // 联系信息
        if (propertyInfoVO.getContactPerson() != null) {
            propertyCompany.setContactPerson(propertyInfoVO.getContactPerson());
        }
        if (propertyInfoVO.getContactPhone() != null) {
            propertyCompany.setContactPhone(propertyInfoVO.getContactPhone());
        }
        if (propertyInfoVO.getContactEmail() != null) {
            propertyCompany.setContactEmail(propertyInfoVO.getContactEmail());
        }
        if (propertyInfoVO.getEmail() != null) {
            propertyCompany.setEmail(propertyInfoVO.getEmail());
        }
        if (propertyInfoVO.getAddress() != null) {
            propertyCompany.setAddress(propertyInfoVO.getAddress());
        }
        if (propertyInfoVO.getBusinessHours() != null) {
            propertyCompany.setBusinessHours(propertyInfoVO.getBusinessHours());
        }
        if (propertyInfoVO.getServiceHotline() != null) {
            propertyCompany.setServiceHotline(propertyInfoVO.getServiceHotline());
        }
        
        // 服务信息
        if (propertyInfoVO.getServiceScope() != null) {
            propertyCompany.setServiceScope(propertyInfoVO.getServiceScope());
        }

        
        // 支付信息
        if (propertyInfoVO.getPaymentAccount() != null) {
            propertyCompany.setPaymentAccount(propertyInfoVO.getPaymentAccount());
        }
        if (propertyInfoVO.getPaymentBank() != null) {
            propertyCompany.setPaymentBank(propertyInfoVO.getPaymentBank());
        }
        if (propertyInfoVO.getPaymentLink() != null) {
            propertyCompany.setPaymentLink(propertyInfoVO.getPaymentLink());
        }
        if (propertyInfoVO.getWechatPayMerchantId() != null) {
            propertyCompany.setWechatPayMerchantId(propertyInfoVO.getWechatPayMerchantId());
        }
        if (propertyInfoVO.getAlipayMerchantId() != null) {
            propertyCompany.setAlipayMerchantId(propertyInfoVO.getAlipayMerchantId());
        }
        
        // 图片信息
        if (propertyInfoVO.getCompanyLogo() != null) {
            propertyCompany.setCompanyLogo(propertyInfoVO.getCompanyLogo());
        }
        if (propertyInfoVO.getPaymentQrCode() != null) {
            propertyCompany.setPaymentQrCode(propertyInfoVO.getPaymentQrCode());
        }
        
        // 描述信息
        if (propertyInfoVO.getIntroduction() != null) {
            propertyCompany.setIntroduction(propertyInfoVO.getIntroduction());
        }
        if (propertyInfoVO.getDescription() != null) {
            propertyCompany.setDescription(propertyInfoVO.getDescription());
        }
        if (propertyInfoVO.getRemark() != null) {
            propertyCompany.setRemark(propertyInfoVO.getRemark());
        }
        
        // 设置更新信息
        propertyCompany.setUpdateBy(userId);
        propertyCompany.setUpdateTime(LocalDateTime.now());

        // 执行更新
        boolean success = propertyCompanyService.updateById(propertyCompany);
        if (success) {
            log.info("更新当前用户物业信息成功，物业公司ID：{}，公司名称：{}", propertyCompanyId, propertyCompany.getCompanyName());
            log.info("更新后的物业公司信息：{}", propertyCompany);
            return Result.success();
        } else {
            log.error("更新物业公司信息失败，物业公司ID：{}", propertyCompanyId);
            return Result.fail("更新失败");
        }
    }

    @Override
    public Result<Map<String, Object>> getPropertyInfoStats() throws Exception {
        log.info("获取物业信息统计");
        
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                return Result.fail("用户未登录");
            }

            // 检查用户是否有关联的物业公司
            Result<Boolean> hasPropertyResult = hasPropertyCompany();
            if (!hasPropertyResult.isSuccess() || !hasPropertyResult.getData()) {
                return Result.fail("用户未关联物业公司");
            }

            // 获取用户关联的物业公司列表
            List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(userId);
            if (userPropertyCompanies == null || userPropertyCompanies.isEmpty()) {
                return Result.fail("未找到关联的物业公司");
            }

            // 获取第一个关联的物业公司ID
            Long propertyCompanyId = userPropertyCompanies.get(0).getPropertyCompanyId();
            if (propertyCompanyId == null) {
                return Result.fail("物业公司ID不能为空");
            }

            // 构建统计信息
            Map<String, Object> stats = new HashMap<>();
            
            // 基础统计信息
            stats.put("totalServiceArea", "50,000㎡"); // 总服务面积
            stats.put("totalCommunities", 5); // 服务社区数
            stats.put("totalHouseholds", 1200); // 服务户数
            stats.put("averageServiceQuality", 95); // 服务质量评分
            stats.put("monthlyIncome", 150000); // 月收入
            stats.put("monthlyExpense", 80000); // 月支出
            stats.put("profitRate", 46.7); // 利润率
            
            // 服务统计
            Map<String, Object> serviceStats = new HashMap<>();
            serviceStats.put("totalEmployees", 25); // 员工总数
            serviceStats.put("activeOrders", 15); // 活跃工单数
            serviceStats.put("completedOrders", 120); // 已完成工单数
            serviceStats.put("customerSatisfaction", 4.8); // 客户满意度
            stats.put("serviceStats", serviceStats);
            
            // 财务统计
            Map<String, Object> financialStats = new HashMap<>();
            financialStats.put("totalRevenue", 1800000); // 年总收入
            financialStats.put("totalExpense", 960000); // 年总支出
            financialStats.put("netProfit", 840000); // 净利润
            financialStats.put("paymentRate", 92.5); // 缴费率
            stats.put("financialStats", financialStats);

            log.info("获取物业信息统计成功，物业公司ID：{}", propertyCompanyId);
            return Result.success(stats);
    }

    @Override
    public Result<Map<String, Object>> getPropertyInfoStats(Long propertyCompanyId) throws Exception {
        log.info("根据物业公司ID获取物业信息统计，物业公司ID：{}", propertyCompanyId);
        
        if (propertyCompanyId == null) {
            return Result.fail("物业公司ID不能为空");
        }

        // 验证物业公司是否存在
        Result<PropertyCompanyVO> propertyCompanyResult = propertyCompanyService.getPropertyCompany(propertyCompanyId);
        if (!propertyCompanyResult.isSuccess() || propertyCompanyResult.getData() == null) {
            return Result.fail("物业公司不存在");
        }

        // 构建统计信息
        Map<String, Object> stats = new HashMap<>();
        
        // 基础统计信息
        stats.put("totalServiceArea", "50,000㎡"); // 总服务面积
        stats.put("totalCommunities", 5); // 服务社区数
        stats.put("totalHouseholds", 1200); // 服务户数
        stats.put("averageServiceQuality", 95); // 服务质量评分
        stats.put("monthlyIncome", 150000); // 月收入
        stats.put("monthlyExpense", 80000); // 月支出
        stats.put("profitRate", 46.7); // 利润率
        
        // 服务统计
        Map<String, Object> serviceStats = new HashMap<>();
        serviceStats.put("totalEmployees", 25); // 员工总数
        serviceStats.put("activeOrders", 15); // 活跃工单数
        serviceStats.put("completedOrders", 120); // 已完成工单数
        serviceStats.put("customerSatisfaction", 4.8); // 客户满意度
        stats.put("serviceStats", serviceStats);
        
        // 财务统计
        Map<String, Object> financialStats = new HashMap<>();
        financialStats.put("totalRevenue", 1800000); // 年总收入
        financialStats.put("totalExpense", 960000); // 年总支出
        financialStats.put("netProfit", 840000); // 净利润
        financialStats.put("paymentRate", 92.5); // 缴费率
        stats.put("financialStats", financialStats);

        log.info("根据物业公司ID获取物业信息统计成功，物业公司ID：{}", propertyCompanyId);
        return Result.success(stats);
    }
}
